#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/21 18:49
# @Author : 闫峰
# @File    : pop_choice_products_list_syc_bei.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/20 13:46
# @Author : 闫峰
# @File    : test_monitor_inf_listing.py
import json
from datetime import datetime, timedelta

import requests
from retrying import retry
from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database
from utils.logging_tool.init_logger import init_logger
from utils.rabbitmq.rabbitmq_utils import RabbitMq_
from utils.times_tool.time_control import count_time

INFO, ERROR, WARNING = init_logger()


# import sys
#
# sys.path.append('testcases/monitor/aliexpress/pop/pop_choice_products_list_syc_x.py')

class Test:

    @count_time
    def test__(self):
        """
        海量监控速卖通平台 在线产品数 550个店铺
        :return:
        """
        mp = RabbitMq_(queue_name="aliexpress_pop_choice_product_monitor_task_all",
                       routing_key="aliexpress_pop_choice_product_monitor_task_all")
        mp.receive_message(self.fun)

        # MyThreadPool(19).multithreaded(self.fun, task_list)

    def fun(self, task_id, UserTokenSecretAccessKey, current_page, source_id, channel_seller_id):
        db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        time_format = "%Y-%m-%d %H:%M:%S"
        now = datetime.now()
        half_hour_ago = now - timedelta(minutes=240)
        formatted_time = half_hour_ago.strftime(time_format)
        datetime_obj = datetime.strptime(formatted_time, time_format)
        result = self.api_(UserTokenSecretAccessKey, current_page, source_id, channel_seller_id)
        if isinstance(result, str):
            if "系统异常" in result:
                # 重新发送到MQ
                mp = RabbitMq_(queue_name="aliexpress_pop_choice_product_monitor_task_all",
                               routing_key="aliexpress_pop_choice_product_monitor_task_all")
                # id,UserTokenSecretAccessKey,page,source_id
                task = (task_id, UserTokenSecretAccessKey, current_page, source_id)
                mp.send_message(str(task))
            update_sql = """
            UPDATE monitor.monitor_aliexpress_listing_all_task
            SET status=2,error_msg=%s,status_code=%s
            WHERE id=%s
            """
            param_tuple = (result, 100001, task_id)
            rows = db_java_test.execute(update_sql, param_tuple)
            return True
        total_page, pop_choice_product = result

        # 更新 m_aliexpress_listing_pop_choice_product_monitor_task 表的状态
        update_sql = """
        UPDATE monitor.monitor_aliexpress_listing_all_task
        SET status=1,error_msg=NULL,status_code=NULL
        WHERE id=%s
        """
        db_java_test.execute(update_sql, (task_id,))
        # pop_choice_product_onSelling = list(filter(
        #     lambda x: x["product_status"] == "onSelling" and Test.str_map_datatime(
        #         x['modified_time']) <= datetime_obj, pop_choice_product))
        data_list = list(map(lambda x: (source_id, x['product_id'], "ONLINE", x['modified_time']), pop_choice_product))
        insert_sql = """
        REPLACE INTO monitor.monitor_aliexpress_listing_all 
        (source_id, product_id,status, modified_time)
        VALUES (%s,%s,%s,%s);
        """
        rows = db_java_test.execute_many(insert_sql, data_list)
        return True

    @retry(stop_max_attempt_number=5, wait_fixed=2000)
    def api_(self, UserTokenSecretAccessKey, current_page, source_id, channel_seller_id):
        print(f"source_id={source_id} current_page={current_page}")
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/ChoiceProductsList"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "channel_seller_id": channel_seller_id,
                "channel": "AE_GLOBAL",
                "page_size": "20",
                "current_page": current_page,
                "search_condition_do": {
                    "product_status": "ONLINE"
                }
            },
            "UserTokenSecretAccessKey": UserTokenSecretAccessKey
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            # return [200, {'status': 'error', 'message': '系统异常：AliExpressApi.PopChoiceProductsList:The operation has timed out.'}]
            try:
                total_page = res.json()['data']['aliexpress_choice_products_list_response']["result"]['total_page']
                pop_choice_product = \
                    res.json()['data']['aliexpress_choice_products_list_response']["result"][
                        'product_list'][
                        'product']
                # {'data': {'aliexpress_pop_choice_products_list_response': {'result': {'success': True, 'total_item': 10055, 'total_page': 202, 'current_page': 204}, 'request_id': '210153c417114599153674748'}, 'body': '{"aliexpress_pop_choice_products_list_response":{"result":{"total_item":10055,"success":true,"total_page":202,"current_page":204},"request_id":"210153c417114599153674748"}}', 'result_success': True, 'isError': False}, 'status': 'success'}
                return total_page, pop_choice_product
            except Exception as e:
                print(
                    f"source_id={source_id} UserTokenSecretAccessKey={UserTokenSecretAccessKey} current_page={current_page} 请求异常\n"
                    f"响应结果为{res.json()} status_code={res.status_code}")

                return str(res.json())

        else:
            # raise Exception("status_code!=200")
            print("status_code!=200")
            return {res.status_code, res.json()}

    @staticmethod
    def str_map_datatime(str_time: str):
        time_format = "%Y-%m-%d %H:%M:%S"
        time_obj = datetime.strptime(str_time, time_format)
        return time_obj
